import 'package:chewie/chewie.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/domain/news/video_controls.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:video_player/video_player.dart';

class VideoPlayUtils {
  static var instance = VideoPlayUtils._();
  VideoPlayUtils._();
  ChewieController? _chewieController;
  VideoPlayerController? _playerController;

  Future<bool> beginPlayVideo(String url) async {
    if (_chewieController != null || _playerController != null) {
      // _playerController?.pause();
      _playerController?.dispose();
      _chewieController?.dispose();
      _chewieController = null;
      _playerController = null;
      await Future.delayed(Duration(milliseconds: 200));
    }

    try {
      _playerController?.pause();
      _playerController = VideoPlayerController.network(url);
      await _playerController?.initialize();

      _chewieController = ChewieController(
        autoPlay: true,
        allowedScreenSleep: false,
        customControls: VideoCustomControls(null, false),
        deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
        videoPlayerController: _playerController!,
      );
      await Future.delayed(Duration(milliseconds: 200));
      _chewieController?.addListener(() {
        DLog(_chewieController);
      });
      _playerController?.addListener(() {
        DLog(_chewieController);
      });
      return true;
    } catch (e) {
      return false;
    }
  }

  disposePlayController() {
    _playerController?.pause();
    _playerController?.dispose();
    _chewieController?.dispose();
  }

  ChewieController? getChewieController() {
    return _chewieController;
  }
}
